import { isArray, isObject } from 'lodash-es'
import { storage } from '@/utils/Storage'

// import { format } from 'date-fns';

export function dateFn(dateObj) {
  const year = dateObj.getFullYear() // 获取年份
  const month = (dateObj.getMonth() + 1).toString().padStart(2, '0') // 获取月份并补零
  const day = dateObj.getDate().toString().padStart(2, '0') // 获取日期并补零
  const hours = dateObj.getHours().toString().padStart(2, '0') // 获取小时数并补零
  const minutes = dateObj.getMinutes().toString().padStart(2, '0') // 获取分钟数并补零
  const seconds = dateObj.getSeconds().toString().padStart(2, '0') // 获取秒数并补零

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

let userInfo = storage.get('userInfo') || ''

const languageType = storage.get('language') || 'zh'

export const http = {
  request: async (options, _otherOptions?) => {
    let key = options.url.slice(0, 1) === '/' ? options.url.slice(1) : options.url

    const keyList = key.split('/')

    keyList.forEach((item, key) => {
      if (key !== 0)
        keyList[key] = `${item.slice(0, 1).toUpperCase()}${item.slice(1)}`
    })

    key = keyList.join('')

    if (!userInfo)
      userInfo = storage.get('userInfo') || ''

    console.log(options)
    console.log('key', key)

    if (isObject(options.data) && options.data.entity && isObject(options.data.entity)) {
      for (const i in options.data.entity) {
        if (options.data.entity[i] === null)
          options.data.entity[i] = ''
      }
    }
    // console.log('window.electron[key]', window.electron[key])
    const res = await window.electron[key](options.data, userInfo, languageType)

    if (res.code === 100) {
      window['$message'].error(res.message)

      throw new Error(res.message)
    }

    if (isObject(res.data)) {
      if (res.data.createTime)
        res.data.createTime = dateFn(res.data.createTime)

      if (res.data.updateTime)
        res.data.updateTime = dateFn(res.data.updateTime)

      if (res.data.list && res.data.list.length) {
        for (const item of res.data.list) {
          if (item.createTime)
            item.createTime = dateFn(item.createTime)

          if (item.updateTime)
            item.updateTime = dateFn(item.updateTime)
        }
      }
    }
    else if (isArray(res.data)) {
      for (const item of res.data) {
        if (item.createTime)

          item.createTime = dateFn(item.createTime)

        if (item.updateTime)
          item.updateTime = dateFn(item.updateTime)
      }
    }

    return res
  },
}
